package com.vrv.netmgr.alarm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.GlobalConstants;
import com.vrv.common.UrlPrefix;
import com.vrv.common.listview.ListViewAdapter;
import com.vrv.common.listview.ListViewUtil;
import com.vrv.common.util.HttpClientToServer;
import com.vrv.common.util.JsonUtil;
import com.vrv.netmgr.R;
import com.vrv.netmgr.alarm.detail.DetailAuditInfoQryActivity;
import com.vrv.netmgr.vo.SerializableAuditInfoQry;
import com.vrv.netmgr.vo.SerializableDeviceIPOccupyQry;
/**
 * @Description 设备IP占用状况查询
 * @author yzj
 * @date
 * 
 */
public class AuditInfoActivity extends Activity {
	// 存储数据的数组列表
	private ArrayList<HashMap<String, Object>> listData = new ArrayList<HashMap<String,Object>>();
	private ListView listView;
	private ListAdapter adapter = new ListAdapter(); 
	private ListViewItemClick listItemClk = new ListViewItemClick();
	//
	public String IP_ADDRESS = "ipAddress";
	public String DEV_ID = "devIp";
	public String DEV_NAME = "deviceName";
	public String MAC_ADDRESS = "macAddress";
	public String HARDWARE_INFO = "description";
	//
	private View loadMoreView;
	//总记录数
	public int RECORD_COUNT;
	//当前页号
	public int CUR_INDEX;
	//等待对话框
	private ProgressDialog progressDialog;
	//查询成功
	private static final int BACK_NULL = 2;
	private static final int QUERY = 3;
	private static final int NET_ERR = 4;
	// 异常判断标记
	private boolean retVal;
	//
	private SerializableDeviceIPOccupyQry info;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.assets_list_page);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.common_title);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		//
		info = (SerializableDeviceIPOccupyQry) getIntent().getSerializableExtra("info");
		init();
		//开始查询数据
		progressDialog = ProgressDialog.show(AuditInfoActivity.this, "", "查询中...", true, true);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getDataFromServer(0, true);
				//返回数据成功消息
				/**返回数据成功消息*/
				if (!retVal){
					handler.sendEmptyMessage(NET_ERR);
				}else{
					if (null == listData || 0 == listData.size()) {
						handler.sendEmptyMessage(BACK_NULL);
					} else {
						handler.sendEmptyMessage(QUERY);
					}
				}
			}
		}).start();
	}
	
	/**listview背景设置*/
	private LinearLayout listBackView;
	
	//处理器
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progressDialog.dismiss();
			switch (msg.what) {
			case QUERY:
				findViews();
				/** listview背景设置 */
				listBackView.setVisibility(listView.getVisibility());
				break;
			case NET_ERR:
				Toast.makeText(AuditInfoActivity.this, "网络连接失败",Toast.LENGTH_LONG).show();
				onBackPressed();
				break;
			case BACK_NULL:
				Toast.makeText(AuditInfoActivity.this, "数据为空", Toast.LENGTH_LONG).show();
				onBackPressed();
				break;				
			}
		}
	};
	//
	private void init(){
		setTitle();
		ImageButton imgbtn_back = (ImageButton) findViewById(R.id.backBtn);
		imgbtn_back.setVisibility(View.VISIBLE);
		imgbtn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		
		listBackView = (LinearLayout) findViewById(R.id.list_background);
	}
	//初始化listview的适配器
	public void initializeAdapter() {
		for (int i = 0; i < listData.size(); i++) {
			adapter.addItem(listData.get(i));
		}
	}
	//添加监听
	private class ListViewItemClick implements AdapterView.OnItemClickListener {
		@SuppressWarnings("unused")
		private boolean netDurIsZero;

		public void setNetDur(boolean netDurIsZero) {
			this.netDurIsZero = netDurIsZero;
		}

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			HashMap<String, Object> hashMap = adapter.getData(arg2);
			//
			SerializableAuditInfoQry serializable = new SerializableAuditInfoQry();
			serializable.setIP_ADDRESS(hashMap.get(IP_ADDRESS).toString());
			serializable.setDEV_ID(hashMap.get(DEV_ID).toString());
			//
			Intent intent = new Intent(AuditInfoActivity.this, DetailAuditInfoQryActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("info", serializable);
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}
	public void loadMorePage(final boolean netDurIsZero) {
		loadMoreView = getLayoutInflater().inflate(R.layout.list_page_load, null);
		final Button loadNextButton = (Button) loadMoreView
				.findViewById(R.id.loadNextButton);
		final Button loadPreButton = (Button) loadMoreView
				.findViewById(R.id.loadPreButton);
		loadNextButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (loadNextButton.getText().equals("查看下一页")) {
					loadNextButton.setText("正在加载中..."); // 设置按钮文字
					loadNextButton.setEnabled(false);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							loadMoreData(true, netDurIsZero);
							adapter.notifyDataSetChanged();
							loadNextButton.setText("查看下一页"); // 恢复按钮文字
							if ((CUR_INDEX + 1) * ListViewUtil.PAGESIZE >= RECORD_COUNT)
								loadNextButton.setVisibility(View.GONE);
							if (CUR_INDEX == 1)
								loadPreButton.setVisibility(View.VISIBLE);
							loadNextButton.setEnabled(true);
						}
					}, 0);
				}
			}
		});
		loadPreButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (loadPreButton.getText().equals("查看上一页")) {
					loadPreButton.setText("正在加载中..."); // 设置按钮文字
					loadPreButton.setEnabled(false);
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							loadMoreData(false, netDurIsZero);
							adapter.notifyDataSetChanged();
							loadPreButton.setText("查看上一页"); // 恢复按钮文字
							if (CUR_INDEX == 0)
								loadPreButton.setVisibility(View.GONE);
							if ((CUR_INDEX + 2) * ListViewUtil.PAGESIZE >= RECORD_COUNT)
								loadNextButton.setVisibility(View.VISIBLE);
							loadPreButton.setEnabled(true);
						}
					}, 0);
				}
			}
		});
		listView.addFooterView(loadMoreView); // 设置列表底部视图
	}
	//加载更多数据
	private void loadMoreData(boolean pageDown, boolean netDurIsZero) {
		int index;
		if (pageDown)
			index = CUR_INDEX + 1;
		else
			index = CUR_INDEX - 1;
		listData.clear();
		adapter.clear();
		getDataFromServer(index, netDurIsZero);
		int datasize = listData.size();
		for (int i = 0; i < datasize; i++)
			adapter.addItem(listData.get(i));
	}
	//查询所有数据
	public void getDataFromServer(int pageNum, boolean netDurIsZero) {
		Map<String, String> map = new HashMap<String, String>();
		map.put(GlobalConstants.PAGE_NUM, pageNum + "");
		map.put(GlobalConstants.ERR_TYPE, "0");
		map.put(GlobalConstants.ERR_MSG, GlobalConstants.OPEN_IO_NET);
		map.put(GlobalConstants.NET_DURATION, netDurIsZero + "");
		retVal = qrynetDurIsZero(map, netDurIsZero);
	}

	public boolean qrynetDurIsZero(Map<String, String> map, boolean netDurIsZero) {
		boolean retVal = false;
		HttpClientToServer httpClientToServer = new HttpClientToServer();
		String urlPrefix = new UrlPrefix(getApplicationContext())
				.getUrlPrefix();
		String urlAddr = urlPrefix + "/deviceInfo/jsonList.do?classId=1&ipaddres="+info.getIP_ADDRESS();
		String response = httpClientToServer.doPost(urlAddr, map);

		if (HttpClientToServer.DO_POST_ERR.equals(response)
				|| HttpClientToServer.DO_POST_EXCEPT.equals(response))
			return retVal;
		try {
			JSONTokener jsonParser = new JSONTokener(response);
			JSONObject jsonObj = (JSONObject) jsonParser.nextValue();
			retVal = jsonObj.getBoolean("success");

			if (!retVal)
				return retVal;
			int count = jsonObj.getInt("totalRecords");

			RECORD_COUNT = count;
			if (count < 1)
				return retVal;
			JSONArray jArr = jsonObj.getJSONArray("records");
			int jArrLen = jArr.length();

			if (jArrLen > 0) {
				CUR_INDEX = Integer.parseInt(map.get(GlobalConstants.PAGE_NUM));

			}
			for (int i = 0; i < jArr.length(); i++) {
				JSONObject jObj = (JSONObject) jArr.opt(i);
				HashMap<String, Object> myMap = new HashMap<String, Object>();
				myMap.put(IP_ADDRESS, info.getIP_ADDRESS());
				myMap.put(DEV_ID, JsonUtil.getJsonString(jObj, "deviceId"));
				myMap.put(DEV_NAME, JsonUtil.getJsonString(jObj, "deviceName"));
				myMap.put(MAC_ADDRESS, JsonUtil.getJsonString(jObj, "macAddress"));
				myMap.put(HARDWARE_INFO, JsonUtil.getJsonString(jObj, "description"));
				listData.add(myMap);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return retVal;
	}

	public void setTitle() {
		TextView title = (TextView) findViewById(R.id.title_text);
		title.setText("设备列表"+"["+info.getIP_ADDRESS()+"]");

		/**
		 * 返回按钮
		 */
		ImageButton backBtn = (ImageButton) findViewById(R.id.backBtn);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
	}

	public void findViews() {
		listView = (ListView) findViewById(R.id.assets_lv_id);
		if (RECORD_COUNT > 0) {
			listView.setVisibility(View.VISIBLE);
			if (RECORD_COUNT > ListViewUtil.PAGESIZE)
				loadMorePage(true);
			adapter.setNetDur(true);
			initializeAdapter();
			listView.setAdapter(adapter);
			listItemClk.setNetDur(true);
			listView.setOnItemClickListener(listItemClk);
		}
	}

	private class ListAdapter extends ListViewAdapter {
		@SuppressWarnings("unused")
		private boolean netDurIsZero;

		public void setNetDur(boolean netDurIsZero) {
			this.netDurIsZero = netDurIsZero;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			final HashMap<String, Object> hashMap = getData(position);
			if (view == null){
				view = LayoutInflater.from(AuditInfoActivity.this).inflate(R.layout.deviceinfoqry_listpage_item, null);
			}
			/**默认背景色设置*/
			view.setBackgroundResource(R.drawable.list_item_state1);
			/**双行背景色设置*/
			if (position % 2 == 0) {
				view.setBackgroundResource(R.drawable.list_item_state);
			}

			TextView name = (TextView) view.findViewById(R.id.tv_name);
			TextView mac = (TextView) view.findViewById(R.id.tv_mac);
			TextView hardware = (TextView) view.findViewById(R.id.tv_hardware);
			name.setText(hashMap.get(DEV_NAME).toString());
			mac.setText(hashMap.get(MAC_ADDRESS).toString());
			hardware.setText(hashMap.get(HARDWARE_INFO).toString());
			return view;
		}
	}
	@Override
	public void onBackPressed() {
		finish();
		overridePendingTransition(R.anim.push_right_out, R.anim.push_right_in);
		super.onBackPressed();
	}
}
